/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * aUnidad.java
 *
 * Created on 16/07/2012, 05:36:22 AM
 */

package interfaz;

import Clases.Planificacion;
import Clases.Unidad;
import Controladores.PlanificacionPersonalizada;
import Controladores.UnidadJpaController;
import escuela.conexion;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/**
 *
 * @author Bryan
 * En este formulario el usuario puede administrar
 * las "Unidades" que la escuela posea
 */
public class aUnidad extends javax.swing.JDialog {

    conexion cnx = conexion.ObtenerInstancia();
    EntityManagerFactory emf = cnx.ObtenerEMF();
    EntityManager em = emf.createEntityManager();
    UnidadJpaController cursos= new UnidadJpaController(emf);
    PlanificacionPersonalizada planifis= new PlanificacionPersonalizada(emf);
    boolean haydatos=true;
    Mensajes msj = new Mensajes(this);
    Unidad actual;
    Unidad seleccionado;

    /** Creates new form aUnidad */

    private void CargarCombo(){

        List<Planificacion> ciclocursoL = planifis.findPlanificacionEntities();
        for(Planificacion cu: ciclocursoL){
            this.planic.addItem(cu.getIdPlanificacion());
            this.planie.addItem(cu.getIdPlanificacion());
        }

    }

     public void cargarTabla()
    {
        Object[] datos= new Object[3];
        DefaultTableModel modelo = new DefaultTableModel();
        modelo.addColumn("Id");
        modelo.addColumn("Unidad");
        modelo.addColumn("No. Planificacion");
        List<Unidad> listacurso = cursos.findUnidadEntities();
            for(Unidad i: listacurso)
            {
                datos[0]=i.getIdUnidad();
                datos[1]=i.getNombre();
                datos[2]=i.getPlanificacion().getIdPlanificacion();
                modelo.addRow(datos);
            }
        this.jTable1.setModel(modelo);
    }

    private void IngresarCurso()
    {
        String nombre=this.NombreC.getText();
        if(nombre.length()>0 && planic.getSelectedIndex()!=-1)
        {
            Unidad nuevo = new Unidad(planifis.GenerarId(), nombre,planifis.findPlanificacion((Short)planic.getSelectedItem()));
            cursos.create(nuevo);
            JOptionPane.showMessageDialog(null, "Se ha ingresado la unidad Correctamente");
        }
        else
        {
            JOptionPane.showMessageDialog(null, "Faltan datos");
        }
    }

    private void ModificarCurso()
    {
        int filaseleccionada = this.jTable1.getSelectedRow();
        if(filaseleccionada > -1)
        {
            try
            {
                if(this.NombreE.getText().length()>0 && planie.getSelectedIndex()!=-1)
                {
                    Short idCurso= (Short) this.jTable1.getValueAt(filaseleccionada,0);
                    actual=cursos.findUnidad(idCurso);
                    actual.setNombre(this.NombreE.getText());
                    actual.setPlanificacion(planifis.findPlanificacion((Short)planie.getSelectedItem()));
                    try {
                        cursos.edit(actual);
                    } catch (Exception ex) {
                        Logger.getLogger(AdminCurso.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    JOptionPane.showMessageDialog(null, "Se ha modificado la unidad Correctamente");
                }
                else
                {
                    JOptionPane.showMessageDialog(null, "Faltan Datos");
                }
            }
            catch (Exception ex) {
                    Logger.getLogger(AdminCurso.class.getName()).log(Level.SEVERE, null, ex);
                }
        }
        else
        {
            JOptionPane.showMessageDialog(null, "Seleccione Fila");
        }
    }

    private void Aceptar(){
        int selec = this.Pestaña.getSelectedIndex();
        switch(selec){
            case 0:
                    IngresarCurso();
                    break;
            case 1:
                    ModificarCurso();
                    break;
        }
        this.cargarTabla();
    }

    private void Cancelar(){
        int selec = this.Pestaña.getSelectedIndex();
        byte respuesta;
        switch(selec){
            case 0: respuesta =msj.MensajeConfirmacion("¿Esta seguro que cancelar el ingreso? Todos los datos se perderan");
                    switch(respuesta){
                        case 0: this.NombreC.setText("");
                                this.planic.setSelectedIndex(-1);
                        break;
                    }
                    break;
            case 1: respuesta = msj.MensajeConfirmacion("¿Esta seguro que desea cancelar la actualizacion? Todos los datos que no esten guardados se perderan");
                    switch(respuesta){
                        case 0: this.NombreE.setText(this.seleccionado.getNombre());
                                this.planie.setSelectedIndex(this.seleccionado.getPlanificacion().getIdPlanificacion());
                                break;
                    }
                    break;
        }
    }

    public aUnidad(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        cargarTabla();
        CargarCombo();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTaskPane1 = new com.l2fprod.common.swing.JTaskPane();
        jLabel1 = new javax.swing.JLabel();
        informacion = new javax.swing.JLabel();
        Pestaña = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jLabel12 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        NombreC = new javax.swing.JTextField();
        planic = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        NombreE = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        planie = new javax.swing.JComboBox();
        cancelar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        aceptar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Administracion de Unidades");

        jLabel1.setFont(new java.awt.Font("Arial", 1, 14));
        jLabel1.setForeground(new java.awt.Color(255, 255, 255));
        jLabel1.setText("Control de Unidades");
        jTaskPane1.add(jLabel1);

        informacion.setForeground(new java.awt.Color(255, 255, 255));
        informacion.setText("jLabel2");
        jTaskPane1.add(informacion);

        Pestaña.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                PestañaStateChanged(evt);
            }
        });
        Pestaña.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                PestañaFocusGained(evt);
            }
        });

        jLabel12.setForeground(new java.awt.Color(255, 0, 0));
        jLabel12.setText("*");
        jLabel12.setToolTipText("Campo Obligatorio");

        jLabel2.setFont(new java.awt.Font("Arial", 0, 12));
        jLabel2.setText("Nombre:");

        NombreC.setFont(new java.awt.Font("Arial", 0, 12));
        NombreC.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                NombreCKeyPressed(evt);
            }
        });

        jLabel5.setText("Planificacion:");

        jLabel13.setForeground(new java.awt.Color(255, 0, 0));
        jLabel13.setText("*");
        jLabel13.setToolTipText("Campo Obligatorio");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 6, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(NombreC, javax.swing.GroupLayout.DEFAULT_SIZE, 288, Short.MAX_VALUE)
                    .addComponent(planic, 0, 288, Short.MAX_VALUE))
                .addContainerGap())
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(33, 33, 33)
                    .addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(360, Short.MAX_VALUE)))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 62, Short.MAX_VALUE)
                    .addComponent(NombreC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel12, javax.swing.GroupLayout.DEFAULT_SIZE, 72, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(planic, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addGap(34, 34, 34))
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                    .addContainerGap(81, Short.MAX_VALUE)
                    .addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap()))
        );

        Pestaña.addTab("Crear", jPanel1);

        NombreE.setFont(new java.awt.Font("Arial", 0, 12));
        NombreE.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                NombreEKeyPressed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Arial", 0, 12));
        jLabel3.setText("Nombre:");

        jLabel4.setFont(new java.awt.Font("Arial", 0, 12));
        jLabel4.setText("Planificacion:");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(planie, 0, 215, Short.MAX_VALUE)
                    .addComponent(NombreE, javax.swing.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE))
                .addGap(62, 62, 62))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(NombreE, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(planie, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(62, Short.MAX_VALUE))
        );

        Pestaña.addTab("Editar", jPanel2);

        cancelar.setText("Cancelar");
        cancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelarActionPerformed(evt);
            }
        });
        cancelar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                cancelarKeyPressed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Id", "Nombre"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Short.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        aceptar.setText("Aceptar");
        aceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                aceptarActionPerformed(evt);
            }
        });
        aceptar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                aceptarKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTaskPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 433, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(266, Short.MAX_VALUE)
                .addComponent(cancelar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(aceptar)
                .addGap(15, 15, 15))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(Pestaña, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 413, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 413, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jTaskPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(Pestaña, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancelar)
                    .addComponent(aceptar))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void NombreCKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_NombreCKeyPressed
        // TODO add your handling code here:
        if(evt.getKeyCode()==10){
            this.aceptar.requestFocusInWindow();
        }
}//GEN-LAST:event_NombreCKeyPressed

    private void NombreEKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_NombreEKeyPressed
        // TODO add your handling code here:

}//GEN-LAST:event_NombreEKeyPressed

    private void PestañaStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_PestañaStateChanged
        // TODO add your handling code here:
        if(this.Pestaña.getSelectedIndex()==1) {
            this.informacion.setText("Seleccione un curso de la tabla, para modificarlo");
            this.aceptar.setEnabled(true);
            this.cancelar.setEnabled(true);
        } else if(this.Pestaña.getSelectedIndex()==0){
            this.informacion.setText("Creacion de un nuevo curso, los campos con * son obligatorios");
            this.aceptar.setEnabled(true);
            this.cancelar.setEnabled(true);
        }
}//GEN-LAST:event_PestañaStateChanged

    private void PestañaFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_PestañaFocusGained
        // TODO add your handling code here:
    }//GEN-LAST:event_PestañaFocusGained

    private void cancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarActionPerformed
        // TODO add your handling code here:
        Cancelar();
}//GEN-LAST:event_cancelarActionPerformed

    private void cancelarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cancelarKeyPressed
        // TODO add your handling code here:
        if(evt.getKeyCode()==10){
            Cancelar();
        }
}//GEN-LAST:event_cancelarKeyPressed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        // TODO add your handling code here:
        int filaseleccionada = this.jTable1.getSelectedRow();
        if(filaseleccionada > -1) {
            try {
                Short idCurso= (Short) this.jTable1.getValueAt(filaseleccionada,0);
                this.seleccionado=cursos.findUnidad(idCurso);
                this.NombreE.setText(this.seleccionado.getNombre());
            } catch (Exception ex) {
                Logger.getLogger(AdminCurso.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            JOptionPane.showMessageDialog(null, "Seleccione Fila");
        }
}//GEN-LAST:event_jTable1MouseClicked

    private void aceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aceptarActionPerformed
        // TODO add your handling code here:
        Aceptar();
}//GEN-LAST:event_aceptarActionPerformed

    private void aceptarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_aceptarKeyPressed
        // TODO add your handling code here:
        if(evt.getKeyCode()==10){
            Aceptar();
        }
}//GEN-LAST:event_aceptarKeyPressed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                aUnidad dialog = new aUnidad(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField NombreC;
    private javax.swing.JTextField NombreE;
    private javax.swing.JTabbedPane Pestaña;
    private javax.swing.JButton aceptar;
    private javax.swing.JButton cancelar;
    private javax.swing.JLabel informacion;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private com.l2fprod.common.swing.JTaskPane jTaskPane1;
    private javax.swing.JComboBox planic;
    private javax.swing.JComboBox planie;
    // End of variables declaration//GEN-END:variables

}
